﻿using System;
using System.Collections.Generic;
using System.Text;
using Glider.Common.Objects;

namespace AnkhBG
{
    class NPCManager
    {
        /// <summary>
        /// Contains all battlemasters except the arena one.
        /// </summary>
        Dictionary<string, GUnit> Battlemasters = new Dictionary<string, GUnit>(6);
        
        /// <summary>
        /// Initializes the class and loads all battlemasters.
        /// </summary>
        public NPCManager()
        {
            GUnit[] Units = GObjectList.GetUnits();

            // Get all Battlemasters
            for(int i = 0; i < Units.Length; i++)
            {
                if (!Battlemasters.ContainsKey("closest"))
                    Battlemasters.Add("closest", Units[i]);

                if(!Units[i].IsDead && Units[i].IsMonster && Units[i].Title.Contains("Battlemaster"))
                {
                    string BGName = Units[i].Title.Substring(0, (Units[i].Title.Length - " Battlemaster".Length));
                    
                    if (!BGName.Equals("Arena"))
                        Battlemasters.Add(BGName, Units[i]);                
                }
            }

            // Set nearest Battlemaster
            GUnit closest = Battlemasters["closest"];
            foreach(KeyValuePair<string, GUnit> Unit in Battlemasters)
            {
                if (Unit.Key.Equals("closest"))
                    continue;

                if (Unit.Value.DistanceToSelf < closest.DistanceToSelf)
                    closest = Unit.Value;
            }
            Battlemasters["closest"] = closest;
        }

        /// <summary>
        /// Retuns battlemaster given by name.
        /// </summary>
        /// <param name="name">Which battlemaster to return (Battleground name or random/closest).</param>
        /// <returns>Requested battlemaster.</returns>
        public GUnit getBattlemaster(string name)
        {
            if (name == "random")
            {
                //Didn't found a better way to pick up random entry from a dictionary.
                Random rnd = new Random();
                int RndNr = rnd.Next(0, Battlemasters.Count - 1);
                int i = 0;

                foreach (KeyValuePair<string, GUnit> Unit in Battlemasters)
                {
                    if (i == RndNr)
                    {
                        return Unit.Value;
                    }

                    i++;
                }

                Main.Instance.Window.Log("Could not pick up a random battlemaster.");
                return null;
            }

            if (Battlemasters.ContainsKey(name))
            {
                return Battlemasters[name];
            }

            Main.Instance.Window.Log("Battlemaster not found: " + name + ". Check settings.");
            return null;
        }
    }
}
